package aliyun.cx.admin.controller;

import aliyun.cx.admin.entity.Tag;
import aliyun.cx.admin.service.TagService;
import aliyun.cx.admin.util.ConfigUtil;
import aliyun.cx.common.util.ResponseUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 标签管理控制器
 */
@RestController
@RequestMapping("/api/admin/tags")
@CrossOrigin(origins = "*", maxAge = 3600)
public class TagController {
    
    @Autowired
    private TagService tagService;
    
    @Autowired
    private ConfigUtil configUtil;
    
    /**
     * 获取标签列表（分页）
     */
    @GetMapping
    public Map<String, Object> getTagList(@RequestParam(defaultValue = "1") Integer current,
                                         @RequestParam(defaultValue = "10") Integer size,
                                         @RequestParam(required = false) String name) {
        try {
            Page<Tag> page = tagService.getTagPage(current, size, name);
            return ResponseUtil.success(page);
        } catch (Exception e) {
            return ResponseUtil.error("获取标签列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有标签列表（不分页）
     */
    @GetMapping("/all")
    public Map<String, Object> getAllTags() {
        try {
            List<Tag> tags = tagService.getAllTags();
            return ResponseUtil.success(tags);
        } catch (Exception e) {
            return ResponseUtil.error("获取标签列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取标签
     */
    @GetMapping("/{id}")
    public Map<String, Object> getTagById(@PathVariable Long id) {
        try {
            Tag tag = tagService.getById(id);
            if (tag != null) {
                return ResponseUtil.success(tag);
            } else {
                return ResponseUtil.error(404, "标签不存在");
            }
        } catch (Exception e) {
            return ResponseUtil.error("获取标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建标签
     */
    @PostMapping
    public Map<String, Object> createTag(@RequestBody Tag tag) {
        try {
            // 检查标签创建功能是否启用
            if (!configUtil.isTagCreateEnabled()) {
                return ResponseUtil.error(403, "标签创建功能已禁用");
            }
            
            // 验证标签名称
            if (tag.getName() == null || tag.getName().trim().isEmpty()) {
                return ResponseUtil.error(400, "标签名称不能为空");
            }
            
            if (tag.getName().length() > 50) {
                return ResponseUtil.error(400, "标签名称不能超过50个字符");
            }
            
            // 检查标签名称是否已存在
            if (tagService.isNameExists(tag.getName().trim(), null)) {
                return ResponseUtil.error(400, "标签名称已存在");
            }
            
            boolean success = tagService.createTag(tag);
            return ResponseUtil.crudResult(success, "创建", tag);
        } catch (Exception e) {
            return ResponseUtil.error("创建标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新标签
     */
    @PutMapping("/{id}")
    public Map<String, Object> updateTag(@PathVariable Long id, @RequestBody Tag tag) {
        try {
            // 验证标签名称
            if (tag.getName() == null || tag.getName().trim().isEmpty()) {
                return ResponseUtil.error(400, "标签名称不能为空");
            }
            
            if (tag.getName().length() > 50) {
                return ResponseUtil.error(400, "标签名称不能超过50个字符");
            }
            
            // 检查标签名称是否已存在（排除当前标签）
            if (tagService.isNameExists(tag.getName().trim(), id)) {
                return ResponseUtil.error(400, "标签名称已存在");
            }
            
            tag.setId(id);
            boolean success = tagService.updateTag(tag);
            return ResponseUtil.crudResult(success, "更新", tag);
        } catch (Exception e) {
            return ResponseUtil.error("更新标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除标签
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteTag(@PathVariable Long id) {
        try {
            // 检查标签是否被文章使用
            if (tagService.isTagInUse(id)) {
                return ResponseUtil.error(400, "该标签下有文章，无法删除");
            }
            
            boolean success = tagService.deleteTag(id);
            return ResponseUtil.crudResult(success, "删除", null);
        } catch (Exception e) {
            return ResponseUtil.error("删除标签失败：" + e.getMessage());
        }
    }
    
    /**
     * 恢复标签
     */
    @PutMapping("/{id}/restore")
    public Map<String, Object> restoreTag(@PathVariable Long id) {
        try {
            boolean success = tagService.restoreTag(id);
            return ResponseUtil.crudResult(success, "恢复", null);
        } catch (Exception e) {
            return ResponseUtil.error("恢复标签失败：" + e.getMessage());
        }
    }
}
